// Lightweight runtime API proxy.
// - In development (import.meta.env.DEV) this module delegates to the mock implementation (mockApi).
// - In production it calls real backend endpoints (basic fetch examples below).
//
// Usage in app: import { listImages, detectAndSaveImage, searchImages, deleteImage } from '../utils/api'
//
// Note: adjust production fetch URLs/shape to match your real backend.

// 🔧 修改：强制使用真实后端（不使用 Mock）
const useMock = false  // 改为 false，始终使用真实后端

async function _loadMock() {
  // dynamic import keeps mock out of production bundles if bundler/tree-shaking supports it
  const m = await import('./mockApi.js')
  return m
}

export async function listImages(...args) {
  if (useMock) {
    const m = await _loadMock()
    return m.listImages(...args)
  }
  const res = await fetch('/api/images')
  if (!res.ok) throw new Error('listImages failed')
  return res.json()
}

export async function detectAndSaveImage(payload) {
  if (useMock) {
    const m = await _loadMock()
    return m.detectAndSaveImage(payload)
  }
  const res = await fetch('/api/detect', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  })
  if (!res.ok) throw new Error('detect failed')
  return res.json()
}

export async function searchImages(params = {}) {
  if (useMock) {
    const m = await _loadMock()
    return m.searchImages(params)
  }
  const qs = new URLSearchParams(params).toString()
  const res = await fetch(`/api/images/search?${qs}`)
  if (!res.ok) throw new Error('searchImages failed')
  return res.json()
}

export async function deleteImage(id) {
  if (useMock) {
    const m = await _loadMock()
    return m.deleteImage(id)
  }
  const res = await fetch(`/api/images/${encodeURIComponent(id)}`, { method: 'DELETE' })
  if (!res.ok) {
    const body = await res.text()
    return { ok: false, reason: body || 'delete failed' }
  }
  return res.json()
}

export async function updateImage(id, patch = {}) {
  if (useMock) {
    const m = await _loadMock()
    return m.updateImage(id, patch)
  }
  const res = await fetch(`/api/images/${encodeURIComponent(id)}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(patch)
  })
  if (!res.ok) throw new Error('updateImage failed')
  return res.json()
}

export async function chatQuery(message, options = { chatOnly: false }) {
  const chatOnly = Boolean(options.chatOnly)

  console.log('🔵 [前端] 开始聊天查询:', { message, chatOnly })

  // 先根据常见标签做简单关键词抽取，优先按 tag 搜索以提高命中率
  const tags = ['裂纹','破损','油污','剥落','划痕','雷击','烧蚀','磨损','腐蚀','分层']
  let foundTag = ''
  for (const t of tags) {
    if (typeof message === 'string' && message.includes(t)) { foundTag = t; break }
  }

  console.log('🔍 [前端] 关键词检测:', { foundTag, chatOnly })

  // 按 tag 或 q 进行检索（chatOnly 下跳过检索以减少干扰）
  let results = []
  if (!chatOnly) {
    try {
      if (foundTag) {
        console.log('🔍 [前端] 按标签搜索:', foundTag)
        results = await searchImages({ tag: foundTag })
      } else {
        console.log('🔍 [前端] 按关键词搜索:', message)
        results = await searchImages({ q: message })
      }
      console.log('✅ [前端] 搜索结果:', results.length, '张图片')
      if (results.length > 0) {
        console.log('   示例图片:', results[0].name, '标签:', results[0].tags)
      }
    } catch (err) {
      console.error('❌ [前端] 搜索失败:', err)
      results = []
    }
  } else {
    console.log('⏭️  [前端] 跳过图片搜索（仅聊天模式）')
  }

  try {
    console.log('📤 [前端] 发送聊天请求到后端...')
    const res = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ message, results, chatOnly })
    })

    console.log('📥 [前端] 后端响应状态:', res.status, res.statusText)

    const raw = await res.text()
    console.log('📄 [前端] 后端原始响应:', raw.substring(0, 200))

    if (!res.ok) {
      console.error('❌ [前端] 后端返回错误状态')
      try { const j = JSON.parse(raw); throw new Error(j.error || j.message || raw) } catch { throw new Error(raw || '后端返回错误') }
    }

    let j
    try { j = JSON.parse(raw) } catch { j = { text: raw } }
    
    console.log('✅ [前端] 解析后的响应:', {
      hasText: !!j.text,
      textLength: j.text?.length || 0,
      hasStructured: !!j.structured,
      resultsCount: (j.results || results || []).length
    })

    // 返回后端的 text、structured 与 results（若后端未返回 structured 则为 undefined）
    return { text: j.text || '未收到后端回复。', results: j.results || results || [], structured: j.structured }
  } catch (err) {
    console.error('❌ [前端] 聊天请求失败:', err)
    return { text: `调用智能助手出错：${err.message}`, results: [] }
  }
}

// 新增：获取聊天历史记录（支持分页和日期筛选）
export async function getChatHistory(limit = 20, page = 1, dateFilter = 'all') {
  if (useMock) {
    const m = await _loadMock()
    if (typeof m.getChatHistory === 'function') return m.getChatHistory(limit, page, dateFilter)
    return { conversations: [], total: 0, hasMore: false }
  }

  try {
    const params = new URLSearchParams({ 
      limit: limit.toString(), 
      page: page.toString(),
      dateFilter 
    })
    const res = await fetch(`/api/chat/history?${params}`)
    if (!res.ok) throw new Error('获取历史记录失败')
    const result = await res.json()
    
    console.log(`📡 API 返回: ${result.conversations?.length || 0} 条, 总计: ${result.total || 0}, 还有更多: ${result.hasMore}`)
    
    return {
      conversations: result.conversations || [],
      total: result.total || 0,
      hasMore: result.hasMore !== false
    }
  } catch (err) {
    console.error('获取聊天历史失败:', err)
    return { conversations: [], total: 0, hasMore: false }
  }
}

// 新增：搜索聊天历史
export async function searchChatHistory(query, limit = 10) {
  if (useMock) {
    const m = await _loadMock()
    if (typeof m.searchChatHistory === 'function') return m.searchChatHistory(query, limit)
    return { conversations: [] }
  }

  try {
    const res = await fetch('/api/chat/search', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query, limit })
    })
    if (!res.ok) throw new Error('搜索历史记录失败')
    return res.json()
  } catch (err) {
    console.error('搜索聊天历史失败:', err)
    return { conversations: [] }
  }
}

// 新增：删除指定对话
export async function deleteChatConversation(id) {
  if (useMock) {
    const m = await _loadMock()
    if (typeof m.deleteChatConversation === 'function') return m.deleteChatConversation(id)
    return { success: false }
  }

  try {
    const res = await fetch(`/api/chat/history/${encodeURIComponent(id)}`, {
      method: 'DELETE'
    })
    if (!res.ok) throw new Error('删除对话失败')
    return res.json()
  } catch (err) {
    console.error('删除对话失败:', err)
    return { success: false }
  }
}

// 新增：清空所有对话历史
export async function clearChatHistory() {
  if (useMock) {
    const m = await _loadMock()
    if (typeof m.clearChatHistory === 'function') return m.clearChatHistory()
    return { success: false }
  }

  try {
    const res = await fetch('/api/chat/history', { method: 'DELETE' })
    if (!res.ok) throw new Error('清空历史记录失败')
    return res.json()
  } catch (err) {
    console.error('清空历史记录失败:', err)
    return { success: false }
  }
}

// ========== 数据管理 API ==========

// 上传图片（支持 AI 检测）
export async function uploadImage({ name, dataUrl, aiEnabled = false }) {
  if (useMock) {
    const m = await _loadMock()
    if (typeof m.detectAndSaveImageWithAI === 'function') {
      return m.detectAndSaveImageWithAI({ name, dataUrl })
    }
  }

  try {
    const res = await fetch('/api/data/upload', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, dataUrl, aiEnabled })
    })
    if (!res.ok) throw new Error('上传图片失败')
    const result = await res.json()
    return result.data
  } catch (err) {
    console.error('上传图片失败:', err)
    throw err
  }
}

// 批量上传图片
export async function uploadImagesBatch(images, aiEnabled = false) {
  if (useMock) {
    const m = await _loadMock()
    const results = []
    for (const img of images) {
      try {
        const result = await m.detectAndSaveImageWithAI({ name: img.name, dataUrl: img.dataUrl })
        results.push({ success: true, data: result })
      } catch (err) {
        results.push({ success: false, error: err.message, name: img.name })
      }
    }
    return { success: true, results }
  }

  try {
    const res = await fetch('/api/data/upload-batch', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ images, aiEnabled })
    })
    if (!res.ok) throw new Error('批量上传失败')
    return res.json()
  } catch (err) {
    console.error('批量上传失败:', err)
    throw err
  }
}

// 获取所有图片
export async function getDataImages() {
  if (useMock) {
    const m = await _loadMock()
    return m.listImages()
  }

  try {
    const res = await fetch('/api/data/images')
    if (!res.ok) throw new Error('获取图片列表失败')
    const result = await res.json()
    return result.data
  } catch (err) {
    console.error('获取图片列表失败:', err)
    throw err
  }
}

// 搜索图片（高级搜索）
export async function searchDataImages({ query = '', tags = [], dateRange = 'all', sortBy = 'createdAt' }) {
  if (useMock) {
    const m = await _loadMock()
    return m.advancedSearch({ query, tags, dateRange, sortBy })
  }

  try {
    const tag = tags && tags.length > 0 ? tags[0] : ''
    
    const res = await fetch('/api/data/search', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ query, tag, dateRange, sortBy })
    })
    if (!res.ok) throw new Error('搜索图片失败')
    const result = await res.json()
    return result.data
  } catch (err) {
    console.error('搜索图片失败:', err)
    throw err
  }
}

// 相似图片搜索
export async function searchSimilarImages(imageId, limit = 5) {
  if (useMock) {
    const m = await _loadMock()
    return m.searchSimilarImages({ id: imageId })
  }

  try {
    const res = await fetch('/api/data/similar', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ imageId, limit })
    })
    if (!res.ok) throw new Error('相似图片搜索失败')
    const result = await res.json()
    return result.data
  } catch (err) {
    console.error('相似图片搜索失败:', err)
    throw err
  }
}

// 删除单张图片
export async function deleteDataImage(imageId) {
  if (useMock) {
    const m = await _loadMock()
    return m.deleteImage(imageId)
  }

  try {
    const res = await fetch(`/api/data/images/${encodeURIComponent(imageId)}`, {
      method: 'DELETE'
    })
    if (!res.ok) throw new Error('删除图片失败')
    return res.json()
  } catch (err) {
    console.error('删除图片失败:', err)
    throw err
  }
}

// 批量删除图片
export async function deleteDataImagesBatch(imageIds) {
  if (useMock) {
    const m = await _loadMock()
    const results = []
    for (const id of imageIds) {
      try {
        await m.deleteImage(id)
        results.push({ success: true, id })
      } catch (err) {
        results.push({ success: false, id, error: err.message })
      }
    }
    return { success: true, results }
  }

  try {
    const res = await fetch('/api/data/delete-batch', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ imageIds })
    })
    if (!res.ok) throw new Error('批量删除失败')
    return res.json()
  } catch (err) {
    console.error('批量删除失败:', err)
    throw err
  }
}

// 获取数据统计
export async function getDataStatistics() {
  if (useMock) {
    const m = await _loadMock()
    return m.getDataStatistics()
  }

  try {
    const res = await fetch('/api/data/statistics')
    if (!res.ok) throw new Error('获取统计信息失败')
    const result = await res.json()
    return result.data
  } catch (err) {
    console.error('获取统计信息失败:', err)
    throw err
  }
}

// 获取图片详情
export async function getDataImageDetail(imageId) {
  if (useMock) {
    const m = await _loadMock()
    const images = await m.listImages()
    return images.find(img => img.id === imageId)
  }

  try {
    const res = await fetch(`/api/data/images/${encodeURIComponent(imageId)}`)
    if (!res.ok) throw new Error('获取图片详情失败')
    const result = await res.json()
    return result.data
  } catch (err) {
    console.error('获取图片详情失败:', err)
    throw err
  }
}

// 更新图片元数据
export async function updateDataImage(imageId, updates) {
  if (useMock) {
    const m = await _loadMock()
    return m.updateImage(imageId, updates)
  }

  try {
    const res = await fetch(`/api/data/images/${encodeURIComponent(imageId)}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updates)
    })
    if (!res.ok) throw new Error('更新图片失败')
    const result = await res.json()
    return result.data
  } catch (err) {
    console.error('更新图片失败:', err)
    throw err
  }
}